package cn.edu.ncu.housinghub.controller.user;

import cn.edu.ncu.housinghub.dto.request.user.ChangePasswordRequest;
import cn.edu.ncu.housinghub.dto.request.user.IdentityVerificationRequest;
import cn.edu.ncu.housinghub.dto.request.user.LoginRequest;
import cn.edu.ncu.housinghub.dto.request.user.RegisterRequest;
import cn.edu.ncu.housinghub.dto.request.user.UserProfileRequest;
import cn.edu.ncu.housinghub.dto.response.user.UserProfileResponse;
import cn.edu.ncu.housinghub.entity.user.User;
import cn.edu.ncu.housinghub.exception.BusinessException;
import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.constant.SystemConstant;

import cn.edu.ncu.housinghub.service.UserService;
import cn.edu.ncu.housinghub.utils.common.TokenUtil;
import cn.edu.ncu.housinghub.utils.security.MailUtil;
import cn.edu.ncu.housinghub.vo.Result;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 注册、登录、个人信息
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenUtil tokenUtil;

    /**
     * 发送验证码
     * @param request 包含邮箱的请求体
     * @return 发送结果
     */
    @PostMapping("/send-code")
    public Result sendVerificationCode(@RequestBody java.util.Map<String, String> request) {
        String email = request.get("email");
        if (email == null || email.trim().isEmpty()) {
            throw new BusinessException(ErrorCodeConstant.INVALID_EMAIL_FORMAT);
        }
        // 发送验证码邮件
        MailUtil.sendVerificationCode(email);
        return Result.success("验证码已发送至您的邮箱");
    }

    /**
     * 用户登录
     * @param loginRequest 登录请求参数
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result login(@Valid @RequestBody LoginRequest loginRequest) {
        // 验证邮箱和密码
        User user = userService.authenticate(loginRequest.getEmail(), loginRequest.getPassword());
        if (user != null) {
            return userService.getToken(user);
        } else {
            throw new BusinessException(ErrorCodeConstant.INVALID_CREDENTIALS);
        }
    }

    /**
     * 用户注册
     * @param registerRequest 注册请求参数
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result register(@Valid @RequestBody RegisterRequest registerRequest) {
        // 检查密码和确认密码是否一致
        if (!registerRequest.isPasswordMatch()) {
            throw new BusinessException(ErrorCodeConstant.PASSWORD_MISMATCH);
        }
        // 验证邮箱验证码
        if (!MailUtil.verifyCode(registerRequest.getEmail(), registerRequest.getVerificationCode())) {
            throw new BusinessException(ErrorCodeConstant.INVALID_VERIFICATION_CODE);
        }
        // 检查邮箱是否已存在
        if (userService.findByEmail(registerRequest.getEmail()) != null) {
            throw new BusinessException(ErrorCodeConstant.EMAIL_ALREADY_EXISTS);
        }
        // 保存用户到数据库
        userService.save(registerRequest);

        // 清除已使用的验证码
        MailUtil.clearCode(registerRequest.getEmail());

        return Result.success("注册成功");
    }

    /**
     * 用户登出
     * @param info 用户token
     * @return 登出结果
     */
    @PostMapping("/logout")
    public Result logout(@RequestHeader("info") String info) {
        userService.logout(info);
        return Result.success("登出成功");
    }

    /**
     * 实名认证
     * @param identityVerificationRequest 实名认证请求参数
     * @param token 用户token
     * @return 认证结果
     */
    @PostMapping("/verify-identity")
    public Result verifyIdentity(@Valid @RequestBody IdentityVerificationRequest identityVerificationRequest,
                                 @RequestHeader("info") String token) {
        if (token == null) {
            throw new BusinessException(ErrorCodeConstant.TOKEN_MISSING);
        }
            // 通过token获取用户信息
            User user = TokenUtil.getUserByToken(token);
            if (user == null) {
                throw new BusinessException(ErrorCodeConstant.INVALID_TOKEN);
            }
            if (user.getIsIdentityVerified()) {
                throw new BusinessException(ErrorCodeConstant.USER_ALREADY_VERIFIED);
            }
            // 执行实名认证
            return userService.verifyIdentity(user,
                    identityVerificationRequest.getRealName(),
                    identityVerificationRequest.getIdentityCard());
    }

    /**
     * 获取用户个人资料
     * @param token 用户token
     * @return 用户个人资料
     */
    @GetMapping("/profile")
    public Result getUserProfile(@RequestHeader("info") String token) {
        if (token == null) {
            throw new BusinessException(ErrorCodeConstant.TOKEN_MISSING);
        }

        UserProfileResponse profile = userService.getUserProfile(token);
        return Result.success(profile);
    }

    /**
     * 更新用户个人资料
     * @param token 用户token
     * @param profileRequest 个人资料更新请求
     * @return 更新结果
     */
    @PutMapping("/profile")
    public Result updateUserProfile(@RequestHeader("info") String token,
                                   @Valid @RequestBody UserProfileRequest profileRequest) {
        if (token == null) {
            throw new BusinessException(ErrorCodeConstant.TOKEN_MISSING);
        }

        return userService.updateUserProfile(token, profileRequest);
    }

    /**
     * 修改用户密码
     * @param token 用户token
     * @param changePasswordRequest 修改密码请求
     * @return 修改结果
     */
    @PutMapping("/change-password")
    public Result changePassword(@RequestHeader("info") String token,
                                @Valid @RequestBody ChangePasswordRequest changePasswordRequest) {
        if (token == null) {
            throw new BusinessException(ErrorCodeConstant.TOKEN_MISSING);
        }

        return userService.changePassword(token, changePasswordRequest);
    }
}
